package com.ctg.polling.domain.util.openid;

import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.dao.DataAccessException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import com.ctg.polling.domain.JPollingUser;

/**
 * Verify & load user information, then populates the UserDetails object.
 * @author jibe
 *
 */
public class UserServiceImpl implements UserDetailsService {

	static final Logger logger = Logger.getLogger(UserServiceImpl.class);

	/*
	@Override
	public UserDetails loadUserByUsername(String username)
			throws UsernameNotFoundException, DataAccessException {
		logger.debug("loading user details");
		
		//  Verify if user is already present in the data-base.
		if (JPollingUser.findJPollingUsersByUsername(username).getResultList().isEmpty()) {
			JPollingUser jPollingUser = new JPollingUser();
			jPollingUser.setUsername(username);
			jPollingUser.persist();
		}
		
		return new UserDetailsPolling(username);
	}*/
	
    public UserDetails loadUserByUsername(String openIdIdentifier) {
        List<JPollingUser> employeeList =
        	JPollingUser.findJPollingUsersByOpenIdIdentifier(openIdIdentifier).getResultList();
        JPollingUser employee = employeeList.size() == 0 ? null : employeeList.get(0);

        if (employee == null) {
            throw new UsernameNotFoundException("User not found for OpenID: " + openIdIdentifier);
        } else {
            return employee;
        }
    }

}
